//
//  PopoverAnimation.m
//  weibo
//
//  Created by hp on 16/4/26.
//  Copyright © 2016年 hp. All rights reserved.
//

#import "PopoverAnimation.h"
#import "PopoverViewController.h"
#import "PopoverPresentationController.h"

@interface PopoverAnimation ()
{
    BOOL isPresent;
}
@end


@implementation PopoverAnimation


#pragma  mark - UIViewControllerTransitioningDelegate
// 告诉系统谁来负责转场动画
- (nullable UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source NS_AVAILABLE_IOS(8_0)
{
    PopoverPresentationController *pc= [[PopoverPresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
    pc.popoverFrame = self.popoverFrame;
    return pc;
}
// 谁来负责弹出动画
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    isPresent = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationPopoverWillShow object:nil];
    return self;
}
// 谁来负责小时动画
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    isPresent = YES;
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationPopoverWillDismiss object:nil];
    return self;
}

#pragma mark - 动画效果
// This is used for percent driven interactive transitions, as well as for container controllers that have companion animations that might need to
// synchronize with the main animation.
// 动画的时间
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    return 0.5;
}
// This method can only  be a nop if the transition is interactive and not a percentDriven interactive transition.
// 具体动画怎么执行
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
    if (!isPresent) {
        
        // 拿到要展现的视图
        UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
        toView.alpha = 0;
        // 将要展现的视图添加到容器上
        [[transitionContext containerView] addSubview:toView];
        
        // 执行动画
        [UIView animateWithDuration:0.5 animations:^{
            // 重置
            toView.alpha = 1.0;
        } completion:^(BOOL finished) {
            // 告诉系统执行完了,不然点击背景不起作用
            [transitionContext completeTransition:YES];
            
        }];
    } else {
        // 关闭
        UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        // 执行动画
        [UIView animateWithDuration:0.5 animations:^{
            
            fromView.alpha = 0;
        } completion:^(BOOL finished) {
            // 告诉系统执行完了
            [transitionContext completeTransition:YES];
        }];
    }
}
@end
